package me.jiatao.baselibrary.data.interceptor

import me.jiatao.baselibrary.common.BaseConstant
import me.jiatao.baselibrary.ext.encodeCookie
import me.jiatao.baselibrary.ext.saveCookie
import okhttp3.Interceptor
import okhttp3.Response

/**
 * SaveCookieInterceptor: 保存 Cookie
 */
class SaveCookieInterceptor : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val response = chain.proceed(request)
        val requestUrl = request.url().toString()
        val domain = request.url().host()
        // set-cookie maybe has multi, login to save cookie
        if (BaseConstant.urlSaveCookie(requestUrl)
            && response.headers(BaseConstant.HTTP_SET_COOKIE_KEY).isNotEmpty()
        ) {
            val cookies = response.headers(BaseConstant.HTTP_SET_COOKIE_KEY)
            val cookie = encodeCookie(cookies)
            saveCookie(requestUrl, domain, cookie)
        }
        return response
    }
}